/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.Rule;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.Actions;
import it.polimi.games.epkb.entityClasses.Predicate;
import java.util.ArrayList;
import java.util.Collection;
import it.polimi.games.epkb.entityClasses.ExecutedRules;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class RuleJpaController implements Serializable {

    public RuleJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public RuleJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Rule rule) throws PreexistingEntityException, Exception {
        if (rule.getPredicateCollection() == null) {
            rule.setPredicateCollection(new ArrayList<Predicate>());
        }
        if (rule.getExecutedRulesCollection() == null) {
            rule.setExecutedRulesCollection(new ArrayList<ExecutedRules>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Actions idAction = rule.getIdAction();
            if (idAction != null) {
                idAction = em.getReference(idAction.getClass(), idAction.getId());
                rule.setIdAction(idAction);
            }
            Collection<Predicate> attachedPredicateCollection = new ArrayList<Predicate>();
            for (Predicate predicateCollectionPredicateToAttach : rule.getPredicateCollection()) {
                predicateCollectionPredicateToAttach = em.getReference(predicateCollectionPredicateToAttach.getClass(), predicateCollectionPredicateToAttach.getId());
                attachedPredicateCollection.add(predicateCollectionPredicateToAttach);
            }
            rule.setPredicateCollection(attachedPredicateCollection);
            Collection<ExecutedRules> attachedExecutedRulesCollection = new ArrayList<ExecutedRules>();
            for (ExecutedRules executedRulesCollectionExecutedRulesToAttach : rule.getExecutedRulesCollection()) {
                executedRulesCollectionExecutedRulesToAttach = em.getReference(executedRulesCollectionExecutedRulesToAttach.getClass(), executedRulesCollectionExecutedRulesToAttach.getId());
                attachedExecutedRulesCollection.add(executedRulesCollectionExecutedRulesToAttach);
            }
            rule.setExecutedRulesCollection(attachedExecutedRulesCollection);
            em.persist(rule);
            if (idAction != null) {
                idAction.getRuleCollection().add(rule);
                idAction = em.merge(idAction);
            }
            for (Predicate predicateCollectionPredicate : rule.getPredicateCollection()) {
                predicateCollectionPredicate.getRuleCollection().add(rule);
                predicateCollectionPredicate = em.merge(predicateCollectionPredicate);
            }
            for (ExecutedRules executedRulesCollectionExecutedRules : rule.getExecutedRulesCollection()) {
                Rule oldIdRuleOfExecutedRulesCollectionExecutedRules = executedRulesCollectionExecutedRules.getIdRule();
                executedRulesCollectionExecutedRules.setIdRule(rule);
                executedRulesCollectionExecutedRules = em.merge(executedRulesCollectionExecutedRules);
                if (oldIdRuleOfExecutedRulesCollectionExecutedRules != null) {
                    oldIdRuleOfExecutedRulesCollectionExecutedRules.getExecutedRulesCollection().remove(executedRulesCollectionExecutedRules);
                    oldIdRuleOfExecutedRulesCollectionExecutedRules = em.merge(oldIdRuleOfExecutedRulesCollectionExecutedRules);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findRule(rule.getId()) != null) {
                throw new PreexistingEntityException("Rule " + rule + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Rule rule) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Rule persistentRule = em.find(Rule.class, rule.getId());
            Actions idActionOld = persistentRule.getIdAction();
            Actions idActionNew = rule.getIdAction();
            Collection<Predicate> predicateCollectionOld = persistentRule.getPredicateCollection();
            Collection<Predicate> predicateCollectionNew = rule.getPredicateCollection();
            Collection<ExecutedRules> executedRulesCollectionOld = persistentRule.getExecutedRulesCollection();
            Collection<ExecutedRules> executedRulesCollectionNew = rule.getExecutedRulesCollection();
            List<String> illegalOrphanMessages = null;
            for (ExecutedRules executedRulesCollectionOldExecutedRules : executedRulesCollectionOld) {
                if (!executedRulesCollectionNew.contains(executedRulesCollectionOldExecutedRules)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain ExecutedRules " + executedRulesCollectionOldExecutedRules + " since its idRule field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idActionNew != null) {
                idActionNew = em.getReference(idActionNew.getClass(), idActionNew.getId());
                rule.setIdAction(idActionNew);
            }
            Collection<Predicate> attachedPredicateCollectionNew = new ArrayList<Predicate>();
            for (Predicate predicateCollectionNewPredicateToAttach : predicateCollectionNew) {
                predicateCollectionNewPredicateToAttach = em.getReference(predicateCollectionNewPredicateToAttach.getClass(), predicateCollectionNewPredicateToAttach.getId());
                attachedPredicateCollectionNew.add(predicateCollectionNewPredicateToAttach);
            }
            predicateCollectionNew = attachedPredicateCollectionNew;
            rule.setPredicateCollection(predicateCollectionNew);
            Collection<ExecutedRules> attachedExecutedRulesCollectionNew = new ArrayList<ExecutedRules>();
            for (ExecutedRules executedRulesCollectionNewExecutedRulesToAttach : executedRulesCollectionNew) {
                executedRulesCollectionNewExecutedRulesToAttach = em.getReference(executedRulesCollectionNewExecutedRulesToAttach.getClass(), executedRulesCollectionNewExecutedRulesToAttach.getId());
                attachedExecutedRulesCollectionNew.add(executedRulesCollectionNewExecutedRulesToAttach);
            }
            executedRulesCollectionNew = attachedExecutedRulesCollectionNew;
            rule.setExecutedRulesCollection(executedRulesCollectionNew);
            rule = em.merge(rule);
            if (idActionOld != null && !idActionOld.equals(idActionNew)) {
                idActionOld.getRuleCollection().remove(rule);
                idActionOld = em.merge(idActionOld);
            }
            if (idActionNew != null && !idActionNew.equals(idActionOld)) {
                idActionNew.getRuleCollection().add(rule);
                idActionNew = em.merge(idActionNew);
            }
            for (Predicate predicateCollectionOldPredicate : predicateCollectionOld) {
                if (!predicateCollectionNew.contains(predicateCollectionOldPredicate)) {
                    predicateCollectionOldPredicate.getRuleCollection().remove(rule);
                    predicateCollectionOldPredicate = em.merge(predicateCollectionOldPredicate);
                }
            }
            for (Predicate predicateCollectionNewPredicate : predicateCollectionNew) {
                if (!predicateCollectionOld.contains(predicateCollectionNewPredicate)) {
                    predicateCollectionNewPredicate.getRuleCollection().add(rule);
                    predicateCollectionNewPredicate = em.merge(predicateCollectionNewPredicate);
                }
            }
            for (ExecutedRules executedRulesCollectionNewExecutedRules : executedRulesCollectionNew) {
                if (!executedRulesCollectionOld.contains(executedRulesCollectionNewExecutedRules)) {
                    Rule oldIdRuleOfExecutedRulesCollectionNewExecutedRules = executedRulesCollectionNewExecutedRules.getIdRule();
                    executedRulesCollectionNewExecutedRules.setIdRule(rule);
                    executedRulesCollectionNewExecutedRules = em.merge(executedRulesCollectionNewExecutedRules);
                    if (oldIdRuleOfExecutedRulesCollectionNewExecutedRules != null && !oldIdRuleOfExecutedRulesCollectionNewExecutedRules.equals(rule)) {
                        oldIdRuleOfExecutedRulesCollectionNewExecutedRules.getExecutedRulesCollection().remove(executedRulesCollectionNewExecutedRules);
                        oldIdRuleOfExecutedRulesCollectionNewExecutedRules = em.merge(oldIdRuleOfExecutedRulesCollectionNewExecutedRules);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = rule.getId();
                if (findRule(id) == null) {
                    throw new NonexistentEntityException("The rule with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Rule rule;
            try {
                rule = em.getReference(Rule.class, id);
                rule.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The rule with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<ExecutedRules> executedRulesCollectionOrphanCheck = rule.getExecutedRulesCollection();
            for (ExecutedRules executedRulesCollectionOrphanCheckExecutedRules : executedRulesCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Rule (" + rule + ") cannot be destroyed since the ExecutedRules " + executedRulesCollectionOrphanCheckExecutedRules + " in its executedRulesCollection field has a non-nullable idRule field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Actions idAction = rule.getIdAction();
            if (idAction != null) {
                idAction.getRuleCollection().remove(rule);
                idAction = em.merge(idAction);
            }
            Collection<Predicate> predicateCollection = rule.getPredicateCollection();
            for (Predicate predicateCollectionPredicate : predicateCollection) {
                predicateCollectionPredicate.getRuleCollection().remove(rule);
                predicateCollectionPredicate = em.merge(predicateCollectionPredicate);
            }
            em.remove(rule);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Rule> findRuleEntities() {
        return findRuleEntities(true, -1, -1);
    }

    public List<Rule> findRuleEntities(int maxResults, int firstResult) {
        return findRuleEntities(false, maxResults, firstResult);
    }

    private List<Rule> findRuleEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Rule.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Rule findRule(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Rule.class, id);
        } finally {
            em.close();
        }
    }

    public int getRuleCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Rule> rt = cq.from(Rule.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
